package com.wyu.notaryserver.service.impl;

import com.wyu.notaryserver.DTO.IdCardDTO;
import com.wyu.notaryserver.DTO.Key_value;
import com.wyu.notaryserver.constant.CaseEnum;
import com.wyu.notaryserver.constant.ClientEnum;
import com.wyu.notaryserver.constant.PictureEnum;
import com.wyu.notaryserver.domain.*;
import com.wyu.notaryserver.exception.BizException;
import com.wyu.notaryserver.service.*;
import com.wyu.notaryserver.util.Base64ToImageUtil;
import com.wyu.notaryserver.util.InfoEnumUtil;
import com.wyu.notaryserver.util.STUtil;
import com.wyu.notaryserver.util.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.support.JstlUtils;

import java.io.IOException;
import java.net.http.HttpClient;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 六味lemontea 2025-01-25
 * @version 1.0
 * @description 保存数据目前是保存group1、group2、group3数组里面的每个group下面的pictures都对应一个client
 * 但是info信息目前还是只有录入身份证信息作为client信息，后续可能添加其他证件，不同的group下面的info可能不同
 * ，需要另外判断证件类型，填入client数据再保存数据库。
 */
@Service
@Transactional
public class SubmitServiceImpl  implements SubmitService {
    @Autowired
    private CaseService caseService;
    @Autowired
    ClientService clientService;
    @Autowired
    PictureService pictureService;
    @Autowired
    private CaseClientService caseClientService;
    @Autowired
    private ClientPictureService clientPictureService;
    @Override
    public void saveData(IdCardDTO idcardDTO) throws IOException, InterruptedException {
        //先在里面安排caseId字段。
        String caseId = idcardDTO.getCaseId();
        ClientDO clientDO1 = new ClientDO();
        ClientDO clientDO2 = new ClientDO();
        ClientDO clientDO3 = new ClientDO();
        List<PictureDO> pictureDO1List = new ArrayList<>();
        List<PictureDO> pictureDO2List = new ArrayList<>();
        List<PictureDO> pictureDO3List = new ArrayList<>();
        IdCardDTO.Data data = idcardDTO.getData();
        //存入group1的client和picture数据。

        data.getGroup1().forEach(group -> {
            setPicture(pictureDO1List,group);
            group.getInfo().forEach(key_value -> {
                setClient(clientDO1,key_value);
            });
        });
        clientDO1.setTypeId(InfoEnumUtil.getCodeByDesc("委托人", ClientEnum.class));
        clientDO1.setTypeName("委托人");
        System.out.println(pictureDO1List);
        if (!clientService.save(clientDO1)){
            throw new BizException("clientDO1数据保存失败");
        }
        if (!pictureService.saveBatch(pictureDO1List)) {
            throw new BizException("pictureDO1List数据保存失败");
        }

        //存入group2的client和picture数据
        data.getGroup2().forEach(group -> {
            setPicture(pictureDO2List,group);
            group.getInfo().forEach(key_value -> {
                setClient(clientDO2,key_value);
            });
        });

        clientDO2.setTypeId(InfoEnumUtil.getCodeByDesc("被委托人", ClientEnum.class));
        clientDO2.setTypeName("被委托人");
        if (!clientService.save(clientDO2)){
            throw new BizException("clientDO2数据保存失败");
        }
        if (!pictureService.saveBatch(pictureDO2List)) {
            throw new BizException("pictureDO2List数据保存失败");
        }

        //存入group3的client和picture数据
        data.getGroup3().forEach(group -> {
            setPicture(pictureDO3List,group);
            group.getInfo().forEach(key_value -> {
                setClient(clientDO3,key_value);
            });
        });
        clientDO3.setTypeId(InfoEnumUtil.getCodeByDesc("其他", ClientEnum.class));
        clientDO3.setTypeName("其他");
        if (!clientService.save(clientDO3)){
            throw new BizException("clientDO3数据保存失败");
        }
        if (!pictureService.saveBatch(pictureDO3List)) {
            throw new BizException("pictureDO3List数据保存失败");
        }
        //存入client_picture
        //1
        List<ClientPictureDO> clientPictureDOS = new ArrayList<>();
        saveClientPictureDOS(clientDO1, pictureDO1List, clientPictureDOS);
        //2
        saveClientPictureDOS(clientDO2, pictureDO2List, clientPictureDOS);
        //3
        saveClientPictureDOS(clientDO3, pictureDO3List, clientPictureDOS);
        if (!clientPictureService.saveBatch(clientPictureDOS)){
            throw new BizException("clientPictureDO数据保存失败");
        }
        //存入case数据
        CaseDO caseDO = new CaseDO();
        caseDO.setCaseNumber(caseId);
        caseDO.setNotary(clientDO1.getName());
        caseDO.setCategory(InfoEnumUtil.getCodeByDesc("内民", CaseEnum.class));
        caseDO.setDepartment(InfoEnumUtil.getCodeByDesc("广东省江门市五邑公证处",CaseEnum.class));
        caseDO.setGroupTag(InfoEnumUtil.getCodeByDesc("金融领域",CaseEnum.class));
        caseDO.setCaseTag(InfoEnumUtil.getCodeByDesc("中信开拓部",CaseEnum.class));
        caseDO.setUrgentDegree(InfoEnumUtil.getCodeByDesc("普通", CaseEnum.class));
        caseDO.setUsePlace(InfoEnumUtil.getCodeByDesc("中国", CaseEnum.class));
        caseDO.setIsDisaster(0);
        if (!caseService.save(caseDO)){
            throw new BizException("case数据保存失败");
        }
        //存入client_case数据。
        CaseClientDO caseClientDO1 = new CaseClientDO();
        CaseClientDO caseClientDO2 = new CaseClientDO();
        CaseClientDO caseClientDO3 = new CaseClientDO();
        List<CaseClientDO> caseClientDOS = new ArrayList<>();
        //caseClient案件1
        caseClientDO1.setCaseId(caseDO.getId());
        caseClientDO1.setClientId(clientDO1.getId());
        caseClientDO1.setRoleType(clientDO1.getTypeId());
        caseClientDO1.setRoleName(clientDO1.getTypeName());
        caseClientDOS.add(caseClientDO1);
        //caseClient2
        caseClientDO2.setCaseId(caseDO.getId());
        caseClientDO2.setClientId(clientDO2.getId());
        caseClientDO2.setRoleType(clientDO2.getTypeId());
        caseClientDO2.setRoleName(clientDO2.getTypeName());
        caseClientDOS.add(caseClientDO2);
        //caseClient3
        caseClientDO3.setCaseId(caseDO.getId());
        caseClientDO3.setClientId(clientDO3.getId());
        caseClientDO3.setRoleType(clientDO3.getTypeId());
        caseClientDO3.setRoleName(clientDO3.getTypeName());
        caseClientDOS.add(caseClientDO3);

        if (!caseClientService.saveBatch(caseClientDOS)) {
            throw new BizException("保存caseClient失败");
        }

        //省厅接口部分
        List<List<Key_value>> infoList = new ArrayList<>();
        List<String> FileList = new ArrayList<>();
        List<IdCardDTO.Group> group1 = idcardDTO.getData().getGroup1();
        for (int i = 0; i < group1.size(); i++) {
            infoList.add(group1.get(i).getInfo());
        }
        for (int i = 0; i < group1.size(); i++) {
            FileList.addAll(group1.get(i).getBase64());
        }
        //todo 测试部分，这部分暂时单独逐个调用测试

//         STUtil.STdata(infoList,FileList);   //基本信息上传（返回卷号与受理编号）
        STUtil.IMG_Choose(infoList,FileList);  //省厅图片上传（全流程）
//          STUtil.QuHao();       //取号
//            STUtil.SaveBL(infoList);     //笔录生成
//            STUtil.SaveWTS(infoList);     //  委托书生成
//            STUtil.SaveWS_SLTZD(infoList);    //拟定文书三之一  受理通知单
//              STUtil.SaveWS_SQB(infoList);     //拟定文书三之二  申请表
//              STUtil.SaveWS_SDHZ(infoList);    //拟定文书三之三   送达回执
    }

    private void saveClientPictureDOS(ClientDO clientDO1, List<PictureDO> pictureDO1List, List<ClientPictureDO> clientPictureDOS) {
        pictureDO1List.forEach(pictureDO1 -> {
            ClientPictureDO clientPictureDO1 = new ClientPictureDO();
            clientPictureDO1.setClientId(clientDO1.getId());
            clientPictureDO1.setPictureId(pictureDO1.getId());
            clientPictureDO1.setRoleType(clientDO1.getTypeId());
            clientPictureDO1.setRoleName(clientDO1.getTypeName());
            clientPictureDOS.add(clientPictureDO1);
        });
    }

    public void setPicture(List<PictureDO> pictureDOList, IdCardDTO.Group group){
        for (String base64:(group.getBase64())){
            PictureDO pictureDO = new PictureDO();
            String pictureUrl = Base64ToImageUtil.saveBase64Image(base64);
            pictureDO.setUrl(pictureUrl);
            pictureDO.setTypeName(group.getName());
            pictureDO.setTypeId(InfoEnumUtil.getCodeByDesc(group.getName(), PictureEnum.class));
            pictureDOList.add(pictureDO);
        }

    }
    public void setClient(ClientDO clientDO,Key_value key_value){
        if (key_value.getValue() == null||"".equals(key_value.getValue())){
            throw  new BizException(key_value.getKey()+"不能为空");
        }
        if ("姓名".equals(key_value.getKey())){
            clientDO.setName(key_value.getValue());
            clientDO.setTypeId(ClientEnum.MANDATOR.getEnumValue());
            clientDO.setTypeName(ClientEnum.MANDATOR.getEnumDesc());
        }else if ("性别".equals(key_value.getKey())){
            clientDO.setGender(ClientEnum.MALE.getEnumValue());
        }else if ("民族".equals(key_value.getKey())){
            clientDO.setNationality(InfoEnumUtil.getCodeByDesc(key_value.getValue(),ClientEnum.class));
        }else if ("出生日期".equals(key_value.getKey())){
            if (!ValidationUtil.ValidateBirthDate(key_value.getValue())){
                throw new BizException("出生日期错误");
            }
            try {
                java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Date birthdate = dateFormat.parse(key_value.getValue());
                clientDO.setBirthdate(birthdate);
            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }
        }else if ("身份证号".equals(key_value.getKey())){
            if (!ValidationUtil.validateIdCard(key_value.getValue())){
                throw new BizException("身份证号错误");
            }
            clientDO.setIdcard(key_value.getValue());
        }else if ("地址".equals(key_value.getKey())){
            clientDO.setAddress(key_value.getValue());
        }
    }
}
